<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.couponName" placeholder="优惠券名称" clearable style="width: 180px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.subType" placeholder="福利类型" clearable style="width: 120px;" class="filter-item">
        <el-option v-for="item in subTypeList" :key="item.key" :label="item.value" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.couponRange" placeholder="发放对象" clearable style="width: 120px;" class="filter-item">
        <el-option v-for="item in couponRangeList" :key="item.key" :label="item.value" :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        筛选
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="success" icon="el-icon-edit" @click="handleCreate">
        发放
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      max-height="690"
      highlight-current-row
      style="width: 100%;"
      :default-sort="{prop: 'couponId', order: null}"
      tooltip-effect="light"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" align="center" width="80" fixed prop="couponId" sortable="custom">
        <template slot-scope="{row}">
          <span>{{ row.couponId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优惠券名" align="center">
        <template slot-scope="{row}">
          <span>{{ row.couponName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="展示图片" align="center" width="90px">
        <template slot-scope="{row}">
          <el-image style="max-width: 50px; max-height: 28px" :src="row.couponImg" :preview-src-list="[row.couponImg]" />
        </template>
      </el-table-column>
      <el-table-column label="福利类型" align="center" prop="subType" sortable="custom" width="110px">
        <template slot-scope="{row}">
          <el-tag size="mini" type="success"> {{ subTypeMap[row.subType] }} </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发放对象" align="center" prop="couponRange" sortable="custom" width="110px">
        <template slot-scope="{row}">
          <el-tag size="mini" type="primary"> {{ couponRangeMap[row.couponRange] }} </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="使用范围" align="center" width="120px" show-overflow-tooltip>
        <template slot-scope="{row}">
          <span>{{ row.couponLimit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="兑换商品" align="center" width="110px">
        <template slot-scope="{row}">
          <el-popover placement="bottom" width="550" trigger="click" title="商品信息">
            <div style="margin: 20px">
              <el-row :gutter="20">
                <el-col :span="5" class="col-title"><p>商品编号</p></el-col>
                <el-col :span="7" class="col-content"><p>{{ tempProduct.productNo }}</p></el-col>
                <el-col :span="5" class="col-title"><p>所属商城</p></el-col>
                <el-col :span="7" class="col-content">
                  <p><el-tag type="primary" size="mini" effect="plain">{{ mallIdMap[tempProduct.mallId] }}</el-tag></p>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="5" class="col-title"><p>商品名称</p></el-col>
                <el-col :span="7" class="col-content"><p>{{ tempProduct.productName }}</p></el-col>
                <el-col :span="5" class="col-title"><p>运费</p></el-col>
                <el-col :span="7" class="col-content"><p>{{ roundPrice(tempProduct.deliveryPrice) }}</p></el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="5" class="col-title"><p>规格名称</p></el-col>
                <el-col :span="7" class="col-content"><p>{{ tempProduct.itemName }}</p></el-col>
                <el-col :span="5" class="col-title"><p>规格属性</p></el-col>
                <el-col :span="7" class="col-content"><p>{{ tempProduct.attributes }}: {{ tempProduct.itemAttrs }}</p></el-col>
              </el-row>
            </div>
            <el-button slot="reference" size="mini" @click="getProductItemVO(row.itemId)">查看</el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="有效期" align="center" width="110px">
        <template slot-scope="{row}">
          <span>{{ row.couponDuration }}天</span>
        </template>
      </el-table-column>
      <el-table-column label="领取时间" align="center" width="130px">
        <template slot-scope="{row}">
          <span v-if="row.startTime && row.receiveTime">{{ row.startTime.substr(5, 5) }} 至 {{ row.receiveTime.substr(5, 5) }}</span>
          <span v-else>生日券模板</span>
        </template>
      </el-table-column>
      <el-table-column label="发放人次" align="center" prop="couponPerson" sortable="custom" width="110px">
        <template slot-scope="{row}">
          <span>{{ row.couponPerson }}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用人次" align="center" prop="couponUse" sortable="custom" width="110px">
        <template slot-scope="{row}">
          <span>{{ row.couponUse }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" sortable="custom" width="140px">
        <template slot-scope="{row}">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180px" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            复制
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row.couponId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page-num.sync="listQuery.pageNum" :page-size.sync="listQuery.pageSize" @pagination="showCouponFreeList" />

    <el-dialog title="发放兑换券" :visible.sync="dialogFormVisible" :fullscreen="true" :close-on-press-escape="false">
      <el-form ref="dataForm" :rules="rules" :model="editTemp" label-width="180px" style="width: 90%">
        <el-row :gutter="80">
          <el-col :span="12">
            <el-form-item label="兑换券名" prop="couponName">
              <el-input v-model="editTemp.couponName" />
            </el-form-item>
            <el-form-item label="描述" prop="couponDesc">
              <el-input v-model="editTemp.couponDesc" type="textarea" :row="2" />
            </el-form-item>
            <el-form-item label="展示图片" prop="couponImg">
              <el-input v-model="editTemp.couponImg" placeholder="图片链接" />
              <img-upload-single @onUpload="uploadImg" @onRemove="removeImg" ref="imgUpload" extra-tip="，建议尺寸为689×221"></img-upload-single>
            </el-form-item>
            <el-form-item label="福利类型" prop="subType">
              <el-select v-model="editTemp.subType" placeholder="福利类型" clearable style="width: 120px;" class="filter-item">
                <el-option v-for="item in subTypeList" :key="item.key" :label="item.value" :value="item.key" />
              </el-select>
            </el-form-item>
            <el-form-item label="适用范围" prop="couponLimit">
              <el-input v-model="editTemp.couponLimit" placeholder="如：限XX商品可用" />
            </el-form-item>
            <el-form-item label="商品规格编号" prop="itemId">
              <el-input v-model="editTemp.itemId" placeholder="兑换券兑换商品的细分规格编号" style="width: 230px" />
              <el-popover placement="bottom" width="550" trigger="click" title="商品信息">
                <div style="margin: 20px">
                  <el-row :gutter="20">
                    <el-col :span="5" class="col-title"><p>商品编号</p></el-col>
                    <el-col :span="7" class="col-content"><p>{{ tempProduct.productNo }}</p></el-col>
                    <el-col :span="5" class="col-title"><p>所属商城</p></el-col>
                    <el-col :span="7" class="col-content">
                      <p><el-tag type="primary" size="mini" effect="plain">{{ mallIdMap[tempProduct.mallId] }}</el-tag></p>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="5" class="col-title"><p>商品名称</p></el-col>
                    <el-col :span="7" class="col-content"><p>{{ tempProduct.productName }}</p></el-col>
                    <el-col :span="5" class="col-title"><p>运费</p></el-col>
                    <el-col :span="7" class="col-content"><p>{{ roundPrice(tempProduct.deliveryPrice) }}</p></el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="5" class="col-title"><p>规格名称</p></el-col>
                    <el-col :span="7" class="col-content"><p>{{ tempProduct.itemName }}</p></el-col>
                    <el-col :span="5" class="col-title"><p>规格属性</p></el-col>
                    <el-col :span="7" class="col-content"><p>{{ tempProduct.attributes }}: {{ tempProduct.itemAttrs }}</p></el-col>
                  </el-row>
                </div>
                <el-button slot="reference" @click="getProductItemVO(editTemp.itemId)">查看商品</el-button>
              </el-popover>
            </el-form-item>
            <el-form-item label="有效天数" prop="couponDuration">
              <el-input-number v-model="editTemp.couponDuration" :min="1" :step="1" step-strictly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-row>
              <el-col :span="12">
                <el-form-item label="开始时间" prop="startTime">
                  <el-date-picker v-model="editTemp.startTime" type="date" placeholder="选择领取开始日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="结束时间" prop="receiveTime">
                  <el-date-picker v-model="editTemp.receiveTime" type="date" placeholder="选择领取截止日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm" />
                </el-form-item>
              </el-col>
            </el-row>
            <p style="margin-left: 100px; font-size: 12px"><el-icon class="el-icon-info"></el-icon> 发送对象仅限当前分局的用户</p>
            <el-form-item label="发放对象" prop="couponRange">
              <el-radio v-for="item in couponRangeList" v-model="editTemp.couponRange" :label="item.key">{{ item.value }}</el-radio>
            </el-form-item>
            <el-transfer
              v-if="editTemp.couponRange===3"
              v-model="transferUsersValue"
              v-loading="transferLoading"
              :data="transferUsersAll"
              filterable
              filter-placeholder="输入用户姓名搜索"
              :titles="['用户列表', '已选用户']"
              style="margin-left: 100px"
            />
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="createData()">
          确认发放
        </el-button>
        <el-button @click="dialogFormVisible = false" style="margin-right: 200px">
          取消
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { showCouponFreeList, removeCouponFree, saveAndSendCouponFree } from '@/api/coupon'
import { getProductItemVO } from '@/api/product'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import ImgUploadSingle from '@/components/ImgUpload/ImgUploadSingle'
import { isInteger } from '@/utils/validate'
import { getUsersPlainListPresent } from '@/api/users'

export default {
  name: 'Coupon',
  components: { Pagination, ImgUploadSingle },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        sortProp: '',
        sortOrder: '',
        couponName: '',
        subType: '',
        couponRange: ''
      },
      editTemp: {
        couponName: '',
        couponImg: '',
        couponDesc: '',
        subType: '',
        couponRange: '',
        couponLimit: '',
        itemId: '',
        couponDuration: '',
        startTime: '',
        receiveTime: '',
        userListStr: ''
      },
      tempProduct: {},
      sendRange: 1,
      dialogFormVisible: false,
      sendDialogVisible: false,
      transferUsersAll: [],
      transferUsersValue: [],
      transferLoading: false,
      rules: {
        couponName: [{ required: true, message: '请填写优惠券名', trigger: 'blur' }],
        couponImg: [{ required: true, message: '请上传优惠券展示图片', trigger: 'change' }],
        couponDesc: [{ required: true, message: '请填写优惠券描述', trigger: 'blur' }],
        subType: [{ required: true, message: '请选择福利类型', trigger: 'change' }],
        couponRange: [{ required: true, message: '请选择优惠券发放范围', trigger: 'blur' }],
        itemId: [{ required: true, message: '请填写兑换券兑换的商品细分规格编号', trigger: 'blur' }],
        couponDuration: [{ required: true, message: '请设置优惠券有效时长（天）', trigger: 'blur' }, { validator: isInteger, trigger: 'blur' }],
        startTime: [{ required: true, message: '请选择领取开始时间', trigger: 'change' }],
        receiveTime: [{ required: true, message: '请选择领取截止时间', trigger: 'change' }]
      },
      subTypeList: [
        { key: 0, value: '年节福利' },
        { key: 1, value: '生日福利' },
        // { key: 3, value: '观光旅游' },
        { key: 4, value: '战时慰问' }
      ],
      subTypeMap: {
        0: '年节福利',
        1: '生日福利',
        // 3: '观光旅游',
        4: '战时慰问'
      },
      couponRangeList: [
        { key: 0, value: '在职员工' },
        { key: 1, value: '民警' },
        { key: 2, value: '辅警' },
        { key: 3, value: '选择用户' }
      ],
      couponRangeMap: {
        0: '在职员工',
        1: '民警',
        2: '辅警',
        3: '选择用户'
      },
      mallIdMap: {
        1: '爱心帮扶',
        2: '特价商城',
        3: '积分商城'
      }
    }
  },
  created() {
    this.showCouponFreeList()
  },
  methods: {
    showCouponFreeList() {
      this.listLoading = true
      this.listQuery.departmentId = this.$store.getters.tmpDepartmentId
      showCouponFreeList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.showCouponFreeList()
    },
    sortChange(data) {
      const { prop, order } = data
      this.listQuery.sortProp = prop
      if (order === 'ascending') {
        this.listQuery.sortOrder = '1'
      } else {
        this.listQuery.sortOrder = '-1'
      }
      this.handleFilter()
    },
    resetDialog() {
      this.editTemp = {
        couponName: '',
        couponImg: '',
        couponDesc: '',
        subType: '',
        couponRange: '',
        couponLimit: '',
        itemId: '',
        couponDuration: '',
        startTime: '',
        receiveTime: '',
        userListStr: ''
      }
    },
    handleCreate() {
      this.resetDialog()
      this.initTransfer()
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          let userListStr = ''
          if (this.editTemp.couponRange === 0) {
            userListStr = 'all'
          } else if (this.editTemp.couponRange === 1) {
            userListStr = 'mj'
          } else if (this.editTemp.couponRange === 2) {
            userListStr = 'fj'
          } else {
            this.transferUsersValue.forEach(value => {
              userListStr += value + ','
            })
            if (userListStr.length <= 0) {
              this.$message({
                message: '至少选择一名用户！',
                type: 'warning'
              })
              return
            }
          }
          const data = Object.assign({}, this.editTemp)
          data.userListStr = userListStr
          data.departmentId = this.$store.getters.tmpDepartmentId
          saveAndSendCouponFree(data).then(response => {
            if (response.code === 0) {
              this.$notify({
                title: 'Success',
                message: '优惠券已生成，服务端自动发放中',
                type: 'success',
                duration: 2000
              })
              this.dialogFormVisible = false
              this.showCouponFreeList()
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.resetDialog()
      this.initTransfer()
      this.editTemp = Object.assign({}, row)
      this.editTemp.startTime = ''
      this.editTemp.receiveTime = ''
      this.editTemp.couponRange = ''
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    initTransfer() {
      this.transferLoading = true
      this.transferUsersAll = []
      this.transferUsersValue = []
      getUsersPlainListPresent(this.$store.getters.tmpDepartmentId).then(response => {
        const list = response.data
        for (let i = 0; i < list.length; i++) {
          this.transferUsersAll.push({
            key: list[i].userId,
            label: list[i].realName
          })
        }
        this.transferLoading = false
      })
    },
    handleDelete(couponId) {
      this.$confirm('此删除操作不可逆，拥有此优惠券的用户将无法使用，是否继续?', '提示', {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeCouponFree(couponId).then(() => {
          this.showCouponFreeList()
          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: '删除优惠券成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    roundPrice(price) {
      return (price / 100).toFixed(2)
    },
    removeImg() {
      this.editTemp.couponImg = ''
    },
    uploadImg() {
      this.editTemp.couponImg = this.$refs.imgUpload.url
    },
    getProductItemVO(itemId) {
      this.tempProduct = {}
      getProductItemVO({ itemId: itemId }).then(response => {
        this.tempProduct = Object.assign({}, response.data)
      })
    }
  }
}
</script>

<style>
  .el-transfer-panel{
    width: 220px;
    height: 400px;
  }
  .el-transfer-panel__list.is-filterable{
    height: 400px;
  }
  .col-title {
    text-align: right
  }

  .col-title p {
    font-weight: bolder;
  }

  .col-content p {
    color: #848383
  }
</style>
